package com.github.manx98.okdownloader.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 文件存储处理器
 * 该方法可以将文件保存到本地
 *
 * @author : manx98
 * @date : 2021/5/26
 */
public class FileDataSaveHandler implements DataSaveHandler {
    private final RandomAccessFile randomAccessFile;
    private final FileChannel channel;
    private volatile boolean closed = false;

    /**
     * 使用文件的方式下载文件
     *
     * @param file 存储到的磁盘位置
     */
    public FileDataSaveHandler(File file) throws FileNotFoundException {
        this.randomAccessFile = new RandomAccessFile(file, "rw");
        channel = this.randomAccessFile.getChannel();
    }

    @Override
    public void save(ByteBuffer data, long seek) throws IOException {
        data.flip();
        try {
            channel.write(data, seek);
        } finally {
            data.clear();
        }
    }

    @Override
    public void fileShrink(long fileSize) throws IOException {
        randomAccessFile.setLength(fileSize);
    }

    /**
     * 资源是否已经关闭
     */
    public boolean isClosed() {
        return closed;
    }

    @Override
    public void close() throws Exception {
        if (!closed) {
            synchronized (this) {
                if (!closed) {
                    channel.close();
                    randomAccessFile.close();
                    closed = true;
                }
            }
        }
    }
}
